package com.coastwe.dahua.chapter04;

public class CircleArrayQueue {
    private int[] data;
    private int n;
    private int head;
    private int tail;

    public CircleArrayQueue(int capacity) {
        data = new int[capacity];
        this.n = capacity;
        this.head = 0;
        this.tail = 0;
    }

    public boolean enqueue(int value) {
        if ((this.tail + 1) % n == this.head) {
            System.out.println("队列已经满了");
            return false;
        } 

        data[tail] = value;
        this.tail = (this.tail + 1) % n;
        return true;
    }

    public int dequeue() {
        if (this.head == this.tail) {
            System.out.println("空队列");
            return -1;
        }
        int value = data[head];
        head = (this.head + 1) % n;
        return value;
    }

    public static void main(String[] args) {
        CircleArrayQueue queue = new CircleArrayQueue(5);
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);
        System.out.print(queue.dequeue() + " ");
        System.out.print(queue.dequeue() + " ");
        System.out.print(queue.dequeue() + " ");
        System.out.print(queue.dequeue() + " ");
        System.out.println();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);
        System.out.print(queue.dequeue() + " ");
        System.out.print(queue.dequeue() + " ");
        System.out.print(queue.dequeue() + " ");
    }
}